package com.zone.editor;

import android.view.View;

import androidx.annotation.Nullable;

import com.zone.editor.inter.BrushViewChangeListener;
import com.zone.editor.inter.DrawingView;
import com.zone.editor.inter.EditorView;
import com.zone.editor.inter.EditorViewState;
import com.zone.editor.inter.OnEditorListener;

public class BrushDrawingStateListener implements BrushViewChangeListener {
    private final EditorView editorView;
    private final EditorViewState mViewState;
    private @Nullable
    OnEditorListener mOnEditorListener;

    public BrushDrawingStateListener(EditorView photoEditorView,
                                     EditorViewState viewState) {
        editorView = photoEditorView;
        mViewState = viewState;
    }

    public void setOnEditorListener(@Nullable OnEditorListener onEditorListener) {
        mOnEditorListener = onEditorListener;
    }

    @Override
    public void onViewAdd(DrawingView photoDrawingView) {
        if (mViewState.getRedoViewsCount() > 0) {
            mViewState.popRedoView();
        }
        mViewState.addAddedView(photoDrawingView);
        if (mOnEditorListener != null) {
            mOnEditorListener.onAddViewListener(
                    ViewType.BRUSH_DRAWING,
                    mViewState.getAddedViewsCount()
            );
        }
    }

    @Override
    public void onViewRemoved(DrawingView photoDrawingView) {
        if (mViewState.getAddedViewsCount() > 0) {
            View removeView = mViewState.removeAddedView(
                    mViewState.getAddedViewsCount() - 1
            );
            if (!(removeView instanceof DrawingView)) {
                editorView.removeView(removeView);
            }
            mViewState.pushRedoView(removeView);
        }

        if (mOnEditorListener != null) {
            mOnEditorListener.onRemoveViewListener(
                    ViewType.BRUSH_DRAWING,
                    mViewState.getAddedViewsCount()
            );
        }
    }

    @Override
    public void onStartDrawing() {
        if (mOnEditorListener != null && editorView.getDrawingView().isDrawingEnabled()) {
            mOnEditorListener.onStartViewChangeListener(ViewType.BRUSH_DRAWING);
        }
    }

    @Override
    public void onStopDrawing() {
        if (mOnEditorListener != null) {
            mOnEditorListener.onStopViewChangeListener(ViewType.BRUSH_DRAWING);
        }
    }
}
